package cn.kimming.rpc.demo.ui.controller;

import cn.kimming.rpc.common.constant.LoadBalance;
import cn.kimming.rpc.demo.test.pojo.TestData;
import cn.kimming.rpc.demo.test.service.TestService;
import cn.kimming.rpc.demo.ui.dto.ServiceCallDTO;
import cn.kimming.rpc.demo.ui.service.UiService;
import cn.kimming.rpc.demo.ui.util.Result;
import cn.kimming.rpc.demo.ui.vo.AutoTestVO;
import cn.kimming.rpc.demo.ui.vo.LbServiceVO;
import cn.kimming.rpc.demo.ui.vo.ServiceVO;
import cn.kimming.rpc.demo.ui.vo.TreeDataVO;
import cn.kimming.rpc.remoting.client.RpcClientConfig;
import cn.kimming.rpc.remoting.proxy.RpcProxyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UiController {

    @Autowired
    private UiService uiService;

    public UiController() {
        warmUpTestService();
    }

    /**
     * 预热一百次服务
     */
    private void warmUpTestService() {
        TestService testService = RpcProxyFactory.createClient(TestService.class, RpcClientConfig.configurer().loadBalance(LoadBalance.RANDOM).config());
        for (int i = 0; i < 100; i++) {
            testService.test(new TestData());
        }

    }


    @GetMapping("/servicelist")
    public Result serviceList() {
        List<ServiceVO> list = uiService.listAllServiceVO();
        return new Result(true, list);
    }

    @GetMapping("/registrytreedata")
    public Result registryTreeData() {
        TreeDataVO data = uiService.getRegistryTreeData();
        return new Result(true, data);
    }

    @GetMapping("/getnodeinfo")
    public Result getNodeInfo(@RequestParam String nodePath) {
        Object nodeInfo = uiService.getNodeInfo(nodePath);
        return new Result(true, nodeInfo);
    }

    @PostMapping("/testconsuming")
    public Result testConsuming(@RequestBody ServiceCallDTO dto) {
        long totalConsuming = uiService.testConsuming(dto);
        return new Result(true, totalConsuming);
    }

    @GetMapping("/lbservices")
    public Result getLbServices() {
        List<LbServiceVO> list = uiService.getLbServices();
        return new Result(true, list);
    }

    @GetMapping("/testlbservice")
    public Result testLbService(@RequestParam LoadBalance loadBalance) {
        String serviceId = uiService.testLbService(loadBalance);
        return new Result(true, serviceId);
    }

    @GetMapping("/autotest")
    public Result autoTest() {
        List<AutoTestVO> list = uiService.autoTest();
        return new Result(true, list);
    }
}
